<script setup>
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { registerMenu, getMenu, invokeMenuAction } from '../../assets/menus';
import { getAppSetting, setAppSetting } from '../../tauriApi';
import { isValidCombo, canonicalizeCombo } from '../../assets/hotkeys';

const { t } = useI18n();
const menubar = ref([]);
const message = ref('');
const loading = ref(false);
const invalidIds = ref(new Set());
const duplicateIds = ref(new Set());
const conflictIds = ref(new Set());
let globalHotkeyMap = {};

async function load() {
  loading.value = true; message.value = '';
  try {
    const raw = await getAppSetting('menubar');
    let parsed = [];
    if (raw) { try { parsed = JSON.parse(raw); } catch {} }
    menubar.value = parsed.length ? parsed : (await getMenu('menubar') || []);
    try {
      const hk = await getAppSetting('hotkeys');
      if (hk) globalHotkeyMap = JSON.parse(hk) || {};
    } catch {}
  } catch (e) { message.value = String(e); }
  loading.value = false;
}

async function save() {
  loading.value = true; message.value = '';
  try {
    if (!validate()) { loading.value = false; return; }
    await setAppSetting('menubar', JSON.stringify(menubar.value || []));
    await registerMenu('menubar', menubar.value || []);
    message.value = t('menus.saved');
  } catch (e) { message.value = String(e); }
  loading.value = false;
}

function addMenu() { menubar.value.push({ id: 'menu-' + Date.now(), label: 'Menu', submenu: [] }); }
function removeMenu(idx) { menubar.value.splice(idx, 1); }
function addItem(mIdx) { menubar.value[mIdx].submenu.push({ id: 'item-' + Date.now(), label: 'Item', action: '', accelerator: '' }); }
function removeItem(mIdx, iIdx) { menubar.value[mIdx].submenu.splice(iIdx, 1); }

onMounted(load);

function validate() {
  invalidIds.value = new Set();
  duplicateIds.value = new Set();
  conflictIds.value = new Set();
  const all = [];
  for (const m of menubar.value) {
    if (!m || !Array.isArray(m.submenu)) continue;
    for (const it of m.submenu) {
      if (!it || !it.id) continue;
      const acc = (it.accelerator || '').trim();
      if (acc) {
        if (!isValidCombo(acc)) invalidIds.value.add(it.id);
        all.push({ id: it.id, action: it.action || '', combo: acc, canon: canonicalizeCombo(acc) });
      }
    }
  }
  // duplicates inside menubar
  const seen = new Map();
  for (const r of all) {
    if (!r.canon) continue;
    if (seen.has(r.canon)) {
      duplicateIds.value.add(r.id);
      duplicateIds.value.add(seen.get(r.canon));
    } else {
      seen.set(r.canon, r.id);
    }
  }
  // conflicts with global hotkeys mapping
  for (const [action, combo] of Object.entries(globalHotkeyMap || {})) {
    const canon = canonicalizeCombo(combo);
    for (const r of all) {
      if (r.canon && canon && r.canon === canon && r.action !== action) conflictIds.value.add(r.id);
    }
  }
  const hasErrors = invalidIds.value.size || duplicateIds.value.size || conflictIds.value.size;
  if (hasErrors) {
    const msgs = [];
    if (invalidIds.value.size) msgs.push(t('menus.err_invalid'));
    if (duplicateIds.value.size) msgs.push(t('menus.err_duplicate'));
    if (conflictIds.value.size) msgs.push(t('menus.err_conflict'));
    message.value = msgs.join(' ')+ ' ' + t('menus.err_fix');
  }
  return !hasErrors;
}
</script>

<template>
  <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-neutral-800 dark:bg-neutral-900">
    <div class="mb-3 flex items-baseline justify-between gap-3">
      <div class="flex items-baseline gap-3">
        <h3 class="text-base font-semibold">{{ t('menus.title') }}</h3>
        <span class="text-xs text-slate-500 dark:text-neutral-400">{{ t('menus.menubar') }}</span>
      </div>
      <div class="flex items-center gap-2">
        <button class="h-8 rounded-md bg-indigo-600 px-3 text-xs text-white transition hover:bg-indigo-500 disabled:opacity-50" :disabled="loading" @click="save">{{ loading ? t('menus.saving') : t('menus.save') }}</button>
        <span :class="['text-xs', (invalidIds.size||duplicateIds.size||conflictIds.size) ? 'text-rose-500' : 'text-slate-500 dark:text-neutral-400']">{{ message }}</span>
      </div>
    </div>

    <div class="space-y-3">
      <div v-for="(m, mi) in menubar" :key="m.id" class="rounded-md border border-slate-200 p-2 dark:border-neutral-800">
        <div class="mb-2 flex items-center gap-2">
          <input class="h-8 w-56 rounded-md border bg-white px-3 text-xs dark:border-neutral-700 dark:bg-neutral-800" v-model="m.label" :placeholder="t('menus.label')" />
          <button class="h-8 rounded-md border border-slate-200 bg-white px-2 text-xs hover:bg-slate-100 dark:border-neutral-700 dark:bg-neutral-800 dark:hover:bg-neutral-700" @click="addItem(mi)">{{ t('menus.add_item') }}</button>
          <button class="h-8 rounded-md border border-slate-200 bg-white px-2 text-xs hover:bg-slate-100 dark:border-neutral-700 dark:bg-neutral-800 dark:hover:bg-neutral-700" @click="removeMenu(mi)">{{ t('menus.remove') }}</button>
        </div>
        <div class="grid grid-cols-[1fr_1fr_1fr_80px] gap-2">
          <div class="text-[11px] text-slate-500 dark:text-neutral-500">{{ t('menus.label') }}</div>
          <div class="text-[11px] text-slate-500 dark:text-neutral-500">{{ t('menus.action') }}</div>
          <div class="text-[11px] text-slate-500 dark:text-neutral-500">{{ t('menus.accelerator') }}</div>
          <div class="text-[11px] text-right text-slate-500 dark:text-neutral-500">{{ t('menus.remove') }}</div>
          <template v-for="(it, ii) in m.submenu" :key="it.id">
            <input class="h-8 rounded-md border bg-white px-3 text-xs dark:border-neutral-700 dark:bg-neutral-800" v-model="it.label" :placeholder="t('menus.label')" />
            <input class="h-8 rounded-md border bg-white px-3 text-xs dark:border-neutral-700 dark:bg-neutral-800" v-model="it.action" :placeholder="t('menus.action')" />
            <input :class="['h-8 rounded-md border bg-white px-3 text-xs dark:border-neutral-700 dark:bg-neutral-800', (invalidIds.has(it.id)||duplicateIds.has(it.id)||conflictIds.has(it.id)) ? 'border-rose-500 focus:outline-none focus:ring-1 focus:ring-rose-500' : '']" v-model="it.accelerator" :placeholder="t('menus.accelerator')" />
            <div class="text-right">
              <button class="h-7 rounded-md border border-slate-200 bg-white px-2 text-[11px] hover:bg-slate-100 dark:border-neutral-700 dark:bg-neutral-800 dark:hover:bg-neutral-700" @click="removeItem(mi, ii)">{{ t('menus.remove') }}</button>
            </div>
          </template>
        </div>
      </div>
      <button class="h-8 rounded-md border border-slate-200 bg-white px-2 text-xs hover:bg-slate-100 dark:border-neutral-700 dark:bg-neutral-800 dark:hover:bg-neutral-700" @click="addMenu">{{ t('menus.add_menu') }}</button>
    </div>
  </div>
</template>


